import {
    initSaveActiveTreeAssignOrganization,
    selectCuesActive,
} from '@/services/api/api-cues-active';
import { cuesAttachmentPreview } from '@/services/api/api-cues-attachment';
import { DownloadOutlined } from '@ant-design/icons';
import { PageContainer, ProFormCascader } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import {
    Alert,
    Button,
    Cascader,
    Descriptions,
    Divider,
    Image,
    message,
    Space,
    Spin,
    Tag,
    Typography,
    Upload,
    UploadFile,
} from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import ReceiptClue from '../clue/components/ReceiptClue';
import { parse } from '@/utils/historyUtils';

interface DetailsClueProps {
    name: string;
    onRefurbish: () => void;
}

const DetailsClue: React.FC<DetailsClueProps> = ({  name, onRefurbish }) => {
    const access = useAccess();

    const [details, setDetailsState] = useState<CuesActiveData.ActiveDetails>();
    const [submitAggregationId, setSubmitAggregationIdState] = useState('');
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewData, setPreviewData] = useState<{
        id: string;
        name: string;
        mimeType: string;
        url?: string;
    }>();
    const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
    const [previewLoading, setPreviewLoading] = useState(true);
    const [drawerFormVisible, setDrawerFormVisible] = useState(false);

    const getWindowSize = () => ({
        innerHeight: window.innerHeight,
        innerWidth: window.innerWidth,
    });
    const [windowSize, setWindowSize] = useState(getWindowSize());
    const handleResize = () => {
        setWindowSize(getWindowSize());
    };
    useEffect(() => {
        // 监听
        window.addEventListener('resize', handleResize);
        // 销毁
        return () => window.removeEventListener('resize', handleResize);
    });

    const iframeRef = useRef(null);

    const handleLoad = () => {
        console.log('加载完成');
        setPreviewLoading(false);
    };
    useEffect(() => {
        const iframe = iframeRef.current;
        iframe?.addEventListener('load', handleLoad);
        return () => {
            iframe?.removeEventListener('load', handleLoad);
        };
    }, [previewOnlineUrl]);
    useEffect(() => {
        const { submitId } = parse(location.search) as { submitId: string };
        setSubmitAggregationIdState(submitId);
        loadSubmitDetails(submitId)
        loadInitSaveActiveTreeAssignOrganization(submitId)
    }, [])
    /**
     * 获取 详情
     * @param key
     */
    const loadSubmitDetails = async (submitId:string) => {
        try {
            const response = await selectCuesActive({ id:submitId });
            if (response.code === 0) {
                setDetailsState(response.data);
                document.title = response.data.articleName;
                console.log('=======', details?.cascaderAssignOrganizations);
            }
        } catch (error) { }
    };

    /**
     * 推送单位数据
     */
    const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

    /**
     * 预备Tree结构数据
     * @param data
     */
    function readyTreeData(data: AdminOrganizationData.Organization[]): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val) => {
                treeData.push({
                    label: val.name,
                    value: val.id,
                    disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
                    children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
                });
            });
        }
        return treeData;
    }

    /**
     * 加载 保存 推送 单位
     */
    const loadInitSaveActiveTreeAssignOrganization = async (submitId:string) => {
        try {
            const response = await initSaveActiveTreeAssignOrganization({
                id:submitId,
            });
            if (response.code === 0) {
                setTreeAssignOrganizationDataState(readyTreeData(response.data));
            }
        } catch (error) { }
    };

    return (
        //   <DrawerForm
        //     key="details_details_drawer_form"
        //     title={details?.articleName}
        //     drawerProps={{
        //       // maskClosable: false,
        //       destroyOnClose: true,
        //       width: 900,
        //     }}
        //     open={drawerFormVisible}
        //     trigger={<a>{name}</a>}
        //     onOpenChange={(visible) => {
        //       if (visible) {
        //         loadInitSaveActiveTreeAssignOrganization();
        //         loadSubmitDetails();
        //       } else {
        //         setTreeAssignOrganizationDataState([]);
        //         onRefurbish();
        //       }
        //       setDrawerFormVisible(visible)
        //     }}
        //     submitter={false}
        //   >
        <PageContainer
            style={{ paddingInline: '20%' }}
            header={{
                title: (
                    <div>
                        {details?.articleName}
                    </div>
                ),
                breadcrumb: {
                    dataTopicDetails: [],
                },
                style: {
                    paddingBlockEnd: 0,
                },
            }}
        >
            <Spin
                style={{
                    textAlign: 'center',
                }}
                spinning={details === undefined}
            >
                {details !== undefined && (
                    <>
                        <Descriptions>
                            <Descriptions.Item label="报送组织">
                                {details?.articleOrganizationName}
                            </Descriptions.Item>
                            <Descriptions.Item label="报送人">{details?.articleAccountName}</Descriptions.Item>
                            <Descriptions.Item label="联系方式">{details?.articleAccountPhone}</Descriptions.Item>
                            <Descriptions.Item label="报送时间">{details?.createdTime}</Descriptions.Item>
                            {access.线索征集x配置x管理员 && (
                                <Descriptions.Item label="阅读情况">
                                    <ReceiptClue id={details.id} receipt={details.receipt} />
                                </Descriptions.Item>
                            )}
                        </Descriptions>
                        <Descriptions>
                            <Descriptions.Item label="行业">
                                <Space size={[0, 8]} wrap>
                                    {details?.articleIndustrys?.map((item) => {
                                        return <Tag key={item.value}>{item.label}</Tag>;
                                    })}
                                </Space>
                            </Descriptions.Item>
                        </Descriptions>
                        <Descriptions>
                            <Descriptions.Item label="标签">
                                {details?.articleLabels.map((item) => {
                                    return <Tag key={item.value}>{item.label}</Tag>;
                                })}
                            </Descriptions.Item>
                        </Descriptions>
                        {details?.remarks && (
                            <Descriptions layout="vertical">
                                <Descriptions.Item label="备注">{details?.remarks}</Descriptions.Item>
                            </Descriptions>
                        )}
                        <div
                            style={{
                                marginTop: 24,
                            }}
                        >
                            <ProFormCascader
                                width="xl"
                                label="邀请采访单位："
                                name="assignOrganizationIds"
                                placeholder="选择单位"
                                fieldProps={{
                                    value: details?.cascaderAssignOrganizations,
                                    options: treeAssignOrganizationData,
                                    multiple: true,
                                    removeIcon: false,
                                    allowClear: false,
                                    maxTagCount: 'responsive',
                                    showCheckedStrategy: Cascader.SHOW_CHILD,
                                }}
                            />
                        </div>
                        <Divider />
                        {details?.articleName ? (
                            <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                {details?.articleName}
                            </Typography.Title>
                        ) : (
                            <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                暂无标题
                            </Typography.Title>
                        )}
                        <br />
                        {details?.articleContent ? (
                            <div
                                dangerouslySetInnerHTML={{
                                    __html: `${details?.articleContent}`,
                                }}
                            />
                        ) : (
                            <>暂无内容</>
                        )}

                        {details?.articleAttachments && details?.articleAttachments.length > 0 && (
                            <>
                                <Divider />
                                <div
                                    style={{
                                        textAlign: 'right',
                                    }}
                                >
                                    <Button
                                        type="primary"
                                        key="import"
                                        size="small"
                                        icon={<DownloadOutlined />}
                                        onClick={() => {
                                            details?.articleAttachments.forEach(function (item) {
                                                window.open(item.content, '_blank');
                                            });
                                        }}
                                    >
                                        全部下载
                                    </Button>
                                </div>

                                <Upload
                                    listType="picture"
                                    multiple
                                    fileList={details?.articleAttachments.map((item) => {
                                        return {
                                            uid: item.id,
                                            name: item.name,
                                            url: item.content,
                                            mimeType: item.mimeType,
                                            status: 'done',
                                        };
                                    })}
                                    showUploadList={{
                                        downloadIcon: (
                                            <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                <DownloadOutlined
                                                    style={{
                                                        marginRight: '10px',
                                                    }}
                                                />
                                                点击下载
                                            </div>
                                        ),
                                        showRemoveIcon: false,
                                        showDownloadIcon: true,
                                    }}
                                    onPreview={async (file: UploadFile) => {
                                        setPreviewData({
                                            id: file.uid,
                                            name: file.name,
                                            mimeType: file.mimeType,
                                            url: encodeURI(file.url),
                                        });
                                        setPreviewOpen(true);
                                    }}
                                />
                                <DrawerForm
                                    title={previewData?.name}
                                    drawerProps={{
                                        width: 900,
                                        destroyOnClose: true,
                                    }}
                                    open={previewOpen}
                                    onOpenChange={async (visible) => {
                                        if (visible) {
                                            if (
                                                previewData?.mimeType !== null &&
                                                previewData?.mimeType?.indexOf('image') > -1
                                            ) {
                                                //图片预览
                                            } else {
                                                setPreviewLoading(true);

                                                const response = await cuesAttachmentPreview({
                                                    id: previewData?.id,
                                                });

                                                if (response.code === 0) {
                                                    setPreviewOnlineUrl(response.data);
                                                } else {
                                                    message.error('暂时无法预览');
                                                    setPreviewLoading(false);
                                                }
                                            }
                                        } else {
                                            setPreviewOpen(false);
                                            setPreviewData(undefined);
                                            setPreviewOnlineUrl(undefined);
                                        }
                                    }}
                                    submitter={{
                                        searchConfig: {
                                            submitText: '下载',
                                        },
                                    }}
                                    onFinish={async (values) => {
                                        window.open(previewData?.url, '_blank');
                                    }}
                                >
                                    <Alert
                                        style={{
                                            marginBottom: 20,
                                        }}
                                        message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                        type="warning"
                                        showIcon
                                    />
                                    {previewData?.mimeType !== null &&
                                        previewData?.mimeType?.indexOf('image') > -1 ? (
                                        <Image width="100%" src={previewData?.url} />
                                    ) : (
                                        <Spin spinning={previewLoading}>
                                            <iframe
                                                ref={iframeRef}
                                                src={previewOnlineUrl}
                                                height={windowSize.innerHeight - 220}
                                                width="100%"
                                                frameBorder="0"
                                                // scrolling="false"
                                                allowFullScreen={true}
                                            // scrolling={'no'}
                                            />
                                        </Spin>
                                    )}
                                </DrawerForm>
                            </>
                        )}
                    </>
                )}
            </Spin>
        </PageContainer>
        //   </DrawerForm>
    );
};

export default DetailsClue;
